<template>
  <c-back-wrap :loading="loading" go-page="经销商门店新建管理" :before-call-back="$goBackCall" :current-page="isEdit?'编辑':'新建'">
    <c-title title="基本信息">
      <CustomerBaseInfo ref="customerBaseInfo" v-model="formData1" :detail="detail" :disabled="isEdit" @change="handleCustomerChange" />
    </c-title>
    <c-title title="门店基本信息">
      <QupFormContainer :column="3">
        <el-form ref="formDataShop1" :model="formDataShopDTO" :rules="formRules1" label-width="140px">
          <el-form-item prop="businessType" label="门店经营业务类型" :span="24">
            <c-common-search-mdm
              placeholder="请选择"
              cust-doc-code="QY037"
              @data-change="handleBusinessTypeDataChange"
            >
              <template v-slot="data">
                <el-checkbox-group v-model="formDataShopDTO.businessType" @change="handleBusinessChange">
                  <el-checkbox v-for="d in data" :key="d.code" :label="d.code">{{ d.name }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </c-common-search-mdm>
          </el-form-item>
          <el-form-item prop="name" label="门店名称">
            <el-input v-model.trim="formDataShopDTO.name" placeholder="门店名称" clearable />
          </el-form-item>
          <el-form-item prop="shopClassify" label="门店类型">
            <c-common-search-mdm
              v-model="formDataShopDTO.shopClassify"
              :label.sync="formDataShopDTO.shopClassifyName"
              placeholder="请选择"
              cust-doc-code="QY028"
            />
          </el-form-item>
          <el-form-item prop="countryCode" label="国别">
            <c-common-search-mdm-country
              v-model="formDataShopDTO.countryCode"
              :label.sync="formDataShopDTO.countryName"
            />
          </el-form-item>
          <template v-if="isCN">
            <el-form-item prop="province" label="省份">
              <c-common-search-province
                v-model="formDataShopDTO.province"
                value-key="id"
                :label.sync="formDataShopDTO.provinceName"
              />
            </el-form-item>
            <el-form-item prop="city" label="城市">
              <c-common-search-not-province
                v-model="formDataShopDTO.city"
                value-key="id"
                :label.sync="formDataShopDTO.cityName"
                :disabled="!formDataShopDTO.province"
                :depend-on-observe="formDataShopDTO.province"
                :start-observe="startObserve"
                :parent-id="formDataShopDTO.province"
              />
            </el-form-item>
            <el-form-item prop="county" label="区/县">
              <c-common-search-not-province
                v-model="formDataShopDTO.county"
                value-key="id"
                :label.sync="formDataShopDTO.countyName"
                :disabled="!formDataShopDTO.city"
                :depend-on-observe="formDataShopDTO.city"
                :start-observe="startObserve"
                :parent-id="formDataShopDTO.city"
              />
            </el-form-item>
            <el-form-item prop="town" label="街道/乡镇">
              <c-common-search-not-province
                v-model="formDataShopDTO.town"
                value-key="id"
                :label.sync="formDataShopDTO.townName"
                :disabled="!formDataShopDTO.county"
                :depend-on-observe="formDataShopDTO.county"
                :start-observe="startObserve"
                :parent-id="formDataShopDTO.county"
              />
            </el-form-item>
          </template>
          <el-form-item prop="shopAddr" label="详细地址" :span="24">
            <el-input v-model="formDataShopDTO.shopAddr" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows:2}" placeholder="详细地址" clearable />
          </el-form-item>
          <el-form-item prop="floor" label="所在楼层">
            <el-input v-model="formDataShopDTO.floor" placeholder="所在楼层" clearable />
          </el-form-item>
          <el-form-item prop="cityLevel" label="城市级别">
            <c-dict-select v-model="formDataShopDTO.cityLevel" :label.sync="formDataShopDTO.cityLevelName" dict-type-code="CITY_LEVEL" clearable placeholder="城市级别" style="width:100%" />
          </el-form-item>
          <el-form-item prop="marketLevelCode" label="市场层级">
            <c-dict-select v-model="formDataShopDTO.marketLevelCode" :label.sync="formDataShopDTO.marketLevelName" dict-type-code="MARKET_LEVEL" clearable placeholder="城市级别" style="width:100%" />
          </el-form-item>
          <el-form-item prop="shopInfoPhone" label="门店咨询电话">
            <el-input v-model="formDataShopDTO.shopInfoPhone" placeholder="门店咨询电话" clearable />
          </el-form-item>
          <el-form-item prop="shopServPhone" label="售后电话">
            <el-input v-model="formDataShopDTO.shopServPhone" placeholder="售后电话" clearable />
          </el-form-item>
          <el-form-item prop="outpicArea" label="出图总面积(㎡)">
            <el-input v-model="formDataShopDTO.outpicArea" v-number.float="2" placeholder="出图总面积(㎡)" clearable />
          </el-form-item>
          <el-form-item prop="isDecorationDoorHead" label="是否装修门头">
            <c-dict-select v-model="formDataShopDTO.isDecorationDoorHead" dict-type-code="BOOLEANS" clearable placeholder="是否装修门头" style="width:100%" />
          </el-form-item>
          <el-form-item prop="doorHeadArea" label="门头面积(㎡)">
            <el-input v-model="formDataShopDTO.doorHeadArea" v-number.float="2" placeholder="门头面积(㎡)" clearable />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS060" label="营业执照图片" :span="24">
            <c-file-list v-model="formDataShopDTO.ACCESS060" direct-del :model-id="formDataShopDTO.id" view-type="list" type-code="ACCESS060" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS061" label="专卖店特许经营合同图片" label-width="160px" :span="24">
            <c-file-list v-model="formDataShopDTO.ACCESS061" direct-del :model-id="formDataShopDTO.id" view-type="list" type-code="ACCESS061" />
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <c-title title="门店联系人">
      <ContactsTable ref="shopContactsTable" title="门店联系人" :table-data="shopContactsTableData" :exclude-requireds="['email']" type="edit" />
    </c-title>
    <c-title title="门店报图情况">
      <QupFormContainer :column="1">
        <el-form ref="formDataShop2" :model="formDataShopDTO" :rules="formRules1" label-width="110px">
          <el-form-item prop="isReportPic" label="是否报图">
            <!-- <el-switch v-model="formDataShopDTO.isReportPic" :active-value="1" :inactive-value="0" /> -->
            <c-dict-select v-model="formDataShopDTO.isReportPic" dict-type-code="BOOLEANS" clearable placeholder="是否报图" />
          </el-form-item>
          <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS062" label="特殊建档附件" :span="24">
            <c-file-list v-model="formDataShopDTO.ACCESS062" direct-del tip="如未报图/未交保证金等情况，业务请示申请审核通过的流程附件" :model-id="formDataShopDTO.id" view-type="list" type-code="ACCESS062" />
          </el-form-item>
        </el-form>
      </QupFormContainer>
    </c-title>
    <c-title title="收货地址信息">
      <div class="el-form-item el-form-item--mini">
        <span class="el-form-item__label">现有收货地址信息</span>
      </div>
      <AddrTable ref="oldAddrTable" title="现有收货地址信息" :table-data="oldAddrTableData" type="view" />
      <div class="el-form-item el-form-item--mini" style="padding-top: 10px;display:flex;align-items:center;">
        <span class="el-form-item__label">是否新增收货地址</span>
        <el-switch v-model="isNewAddress" :active-value="1" :inactive-value="0" />
      </div>
      <AddrTable v-show="isNewAddress===1" ref="newAddrTable" title="新增收货地址" :table-data="newAddrTableData" type="edit" />
    </c-title>
    <c-title title="交接信息">
      <QupFormContainer :column="1">
        <el-form ref="formHandover" :model="formData" :rules="formRules" label-width="130px">
          <el-form-item prop="isMarketConnect" label="是否属于交接门店">
            <!-- <el-switch v-model="formData.isMarketConnect" :active-value="1" :inactive-value="0" /> -->
            <c-dict-select v-model="formData.isMarketConnect" dict-type-code="BOOLEANS" :clearable="false" />
          </el-form-item>
          <template v-if="[1,'1'].includes(formData.isMarketConnect)">
            <el-form-item label-width="0" style="width:100%;">
              <DistributionTable ref="distributionTable" filter-q-y-q-j-k-u title="交接信息" :office-code="formData1.officeCode" :table-data="distributionTableData" :hidden-column="['toAccountCode', 'toAccountName']" type="edit" />
            </el-form-item>
            <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS063" label="经销商交接证明" :span="24">
              <c-file-list v-model="formData.ACCESS063" direct-del :model-id="id" view-type="list" type-code="ACCESS063" tip="交接证明签订一式三份，双方各自保留一份，邮寄公司一份" />
            </el-form-item>
            <el-form-item v-if="!id || Object.keys(detail).length>0" prop="ACCESS064" label="经销商关系证明" :span="24">
              <c-file-list v-model="formData.ACCESS064" direct-del :model-id="id" view-type="list" type-code="ACCESS064" />
            </el-form-item>
            <el-form-item v-if="!id || Object.keys(detail).length>0" key="ACCESS111" prop="ACCESS111" label="交接双方现场签订照片" label-width="160px" :span="24">
              <c-file-list v-model="formData.ACCESS111" direct-del :model-id="id" view-type="list" type-code="ACCESS111" />
            </el-form-item>
            <el-form-item v-if="!id || Object.keys(detail).length>0" prop="1" label="交接双方现场签订照片模板下载" label-width="180px" :span="24">
              <div class="template-down" @click.stop="handleDownTemplate(ACCESS111.id)">
                <span>交接双方现场签订照片模板下载</span>
                <i class="el-icon-download" />
              </div>
            </el-form-item>
          </template>
        </el-form>
      </QupFormContainer>
    </c-title>

    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleSave">保存草稿</c-button>
      <c-button type="primary" @click="handleSubmit">提交</c-button>
    </div>
  </c-back-wrap>
</template>
<script>
import { shopDetail, shopSave, shopSubmit } from '@/api/channelTask2/newShop'
import { customerAddress, downTemplate, getTemplateConfig } from '@/api/channelTask2/change'
import AddrTable from '../../components/AddrTable'
import DistributionTable from '../../components/DistributionTable'

import ContactsTable from '../../components/ContactsTable'
import CustomerBaseInfo from '../../components/CustomerBaseInfo'

export default {
  name: 'AddEdit',
  components: {
    AddrTable,
    ContactsTable,
    DistributionTable,
    CustomerBaseInfo
  },
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      startObserve: false,
      detail: {},
      loading: false,
      formData1: {},
      formData: {
        isMarketConnect: '',
        // 交接附件
        ACCESS063: [],
        ACCESS064: [],
        ACCESS111: []
      },
      formDataShopDTO: {
        businessType: [],
        businessTypeName: [],
        name: '',
        shopClassify: '',
        shopClassifyName: '',
        countryCode: 'CN',
        countryName: '中国',
        province: '',
        provinceName: '',
        city: '',
        cityName: '',
        county: '',
        countyName: '',
        town: '',
        townName: '',
        shopAddr: '',
        floor: '',
        cityLevel: '',
        cityLevelName: '',
        marketLevelCode: '',
        marketLevelName: '',
        shopInfoPhone: '',
        shopServPhone: '',
        outpicArea: '',
        isDecorationDoorHead: '',
        doorHeadArea: '',
        id: '',
        isReportPic: '',
        ACCESS060: [],
        ACCESS061: []
      },
      businessTypeData: [],
      shopLoading: false,
      isNewAddress: 0,
      oldAddrTableData: [],
      newAddrTableData: [],
      shopContactsTableData: [],
      distributionTableData: [],
      ACCESS111: {}
    }
  },
  computed: {
    isEdit() {
      return !!this.id
    },
    isCN() {
      return this.formDataShopDTO.countryCode === 'CN'
    },
    formRules1() {
      return {
        // 门店信息
        businessType: [{ required: true, validator: (r, v, c) => {
          if (!v || v.length <= 0) {
            c(new Error('请选择门店经营业务类型'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        name: [{ required: true, message: '请输入门店名称', trigger: 'change' }],
        shopClassify: [{ required: true, message: '请选择门店类型', trigger: 'change' }],
        countryCode: [{ required: true, message: '请选择国别', trigger: 'change' }],
        province: [{ required: this.isCN, message: '请选择省份', trigger: 'change' }],
        city: [{ required: this.isCN, message: '请选择城市', trigger: 'change' }],
        county: [{ required: this.isCN, message: '请选择区/县', trigger: 'change' }],
        town: [{ required: this.isCN, message: '请选择街道/乡镇', trigger: 'change' }],
        shopAddr: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
        floor: [{ required: true, message: '请输入所在楼层', trigger: 'change' }],
        cityLevel: [{ required: true, message: '请选择城市级别', trigger: 'change' }],
        marketLevelCode: [{ required: true, message: '请选择市场层级', trigger: 'change' }],
        shopInfoPhone: [{ required: true, validator: (r, v, c) => {
          if (!v || (v && /^\d{3,4}-?\d{7,8}$|^1\d{10}$/.test(v))) {
            c()
          } else {
            c(new Error('请检查号码格式'))
          }
        }, trigger: 'change' }],
        shopServPhone: [{ required: true, validator: (r, v, c) => {
          if (!v || (v && /^\d{3,4}-?\d{7,8}$|^1\d{10}$/.test(v))) {
            c()
          } else {
            c(new Error('请检查号码格式'))
          }
        }, trigger: 'change' }],
        outpicArea: [{ required: true, message: '请输入出图总面积', trigger: 'change' }],
        isDecorationDoorHead: [{ required: true, message: '请选择是否装修门头', trigger: 'change' }],
        doorHeadArea: [{ required: [1, '1'].includes(this.formDataShopDTO.isDecorationDoorHead), message: '请输入门头面积', trigger: 'change' }],
        ACCESS060: [{ required: true, validator: (r, v, c) => {
          if (!v || v.length <= 0) {
            c(new Error('请上传营业执照图片'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        ACCESS061: [{ required: true, validator: (r, v, c) => {
          if (!v || v.length <= 0) {
            c(new Error('请上传专卖店特许经营合同图片'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        // 报图相关
        isReportPic: [{ required: true, message: '请选择是否报图', trigger: 'change' }]
        // ACCESS062: [{ required: true, validator: (r, v, c) => {
        //   if (!v || v.length <= 0) {
        //     c(new Error('请上传特殊建档附件'))
        //   } else {
        //     c()
        //   }
        // }, trigger: 'change' }]
      }
    },
    formRules() {
      return {
        // 交接附件
        ACCESS063: [{ required: true, validator: (r, v, c) => {
          if (!v || v.length <= 0) {
            c(new Error('请上传交接证明'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        ACCESS064: [{ required: this.hasIsTransferSales, validator: (r, v, c) => {
          if (!this.hasIsTransferSales) {
            c()
            return
          }
          if (!v || v.length <= 0) {
            c(new Error('请上传经销商关系证明'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        ACCESS111: [{ required: this.hasIsMarketConnect, validator: (r, v, c) => {
          if (!this.hasIsMarketConnect) {
            c()
            return
          }
          if (!v || v.length <= 0) {
            c(new Error('请上传交接双方现场签订照片'))
          } else {
            c()
          }
        }, trigger: 'change' }],
        isMarketConnect: [{ required: true, message: '请选择是否属于交接门店', trigger: 'change' }]
      }
    },
    hasIsTransferSales() {
      return this.distributionTableData.some(e => [1, '1'].includes(e.isTransferSales))
    },
    hasIsMarketConnect() {
      return [1, '1'].includes(this.formData.isMarketConnect)
    }
  },
  created() {
    if (!this.id) {
      this.startObserve = true
    } else {
      this.getDetailData().then(() => {
        setTimeout(() => {
          this.startObserve = true
        }, 0)
      })
    }
    this.templateConfig()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.formDataShop1 && this.$refs.formDataShop1.clearValidate && this.$refs.formDataShop1.clearValidate()
      this.$refs.formDataShop2 && this.$refs.formDataShop2.clearValidate && this.$refs.formDataShop2.clearValidate()
      this.$refs.formHandover && this.$refs.formHandover.clearValidate && this.$refs.formHandover.clearValidate()
    })
  },
  methods: {
    handleCustomerChange(customerCode) {
      this.oldAddrTableData = []
      this.newAddrTableData = []
      this.shopContactsTableData = []
      this.distributionTableData = []
      if (!customerCode) {
        return
      }
      customerAddress(customerCode).then(res => {
        this.oldAddrTableData = res.data
      })
    },
    handleBusinessChange(v) {
      this.formDataShopDTO.businessTypeName = this.businessTypeData.filter(e => v.includes(e.code)).map(e => e.name)
    },
    getDetailData() {
      this.loading = true
      return shopDetail(this.id).then(res => {
        this.detail = res.data
        this.initFormData()
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    initFormData() {
      // formDataShopDTO
      const shopDTO = this.detail.shopDTO || {}
      Object.entries(this.formDataShopDTO).forEach(([k, _v]) => {
        let v = shopDTO[k]
        if (['businessType', 'businessTypeName'].includes(k)) {
          v = (v || '').split(',')
        }
        this.$set(this.formDataShopDTO, k, v !== undefined ? v : _v)
      })
      Object.entries(this.formData).forEach(([k, _v]) => {
        const v = this.detail[k]
        this.$set(this.formData, k, v !== undefined ? v : _v)
      })
      // 门店联系人
      this.shopContactsTableData = this.detail.contactDTOS || []
      // 收货地址
      this.oldAddrTableData = (this.detail.addressDTOS || []).filter(e => [1, '1'].includes(e.isBefore))
      this.newAddrTableData = (this.detail.addressDTOS || []).filter(e => ![1, '1'].includes(e.isBefore))
      this.isNewAddress = this.newAddrTableData.length > 0 ? 1 : 0
      // 交接信息
      this.distributionTableData = this.detail.handoverDTOS || []
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    handleBusinessTypeDataChange(v) {
      this.businessTypeData = v
    },
    async validate() {
      await this.$refs.customerBaseInfo.validate()
      await this.$refs.formDataShop1.validate()
      await this.$refs.formDataShop2.validate()
      await this.$refs.formHandover.validate()
      // 至少有一条联系人类别为“责任人”的数据
      if (!this.shopContactsTableData.some(e => [1, '1'].includes(e.contactTypeCode))) {
        const msg = '至少有一条【门店-联系人类别】为【责任人】!'
        this.$message.warning(msg)
        return Promise.reject(msg)
      }

      // 交接信息
      if ([1, '1'].includes(this.formData.isMarketConnect) && this.distributionTableData.length === 0) {
        const msg = '【交接信息】至少有一条数据!'
        this.$message.warning(msg)
        return Promise.reject(msg)
      }

      // 校验table
      const keys = 'newAddrTable shopContactsTable distributionTable'.split(' ')
      for (const k of keys) {
        const ref = this.$refs[k]
        if (ref && ref.validate) {
          await ref.validate()
        }
      }
      return Promise.resolve(true)
    },
    getPostData(isSave = true) {
      const data = {
        addressDTOS: [],
        attachmentDTOS: [],
        contactDTOS: [],
        handoverDTOS: [],
        shopDTO: {}
      }
      if (this.isEdit) {
        Object.assign(data, this.detail)
      }
      Object.assign(data, this.formData, this.formData1)
      // 收货地址信息
      data.addressDTOS = []
      if ([1, '1'].includes(this.isNewAddress)) {
        data.addressDTOS.push(...this.newAddrTableData.map(e => {
          e.isBefore = 0
          return e
        }))
      }
      if (!isSave) {
        data.addressDTOS.push(...this.oldAddrTableData.map(e => {
          e.isBefore = 1
          return e
        }))
      }
      // 门店联系人
      data.contactDTOS = this.shopContactsTableData

      // 交接信息
      const isMCTrue = [1, '1'].includes(data.isMarketConnect)
      data.handoverDTOS = isMCTrue ? this.distributionTableData : []

      // 门店信息
      if (this.isEdit) {
        data.shopDTO = { ...this.$deepClone((this.detail.shopDTO || {})), ...this.$deepClone(this.formDataShopDTO) }
      } else {
        data.shopDTO = this.$deepClone(this.formDataShopDTO)
      }
      if (data.shopDTO.businessType instanceof Array) {
        data.shopDTO.businessType = data.shopDTO.businessType.join(',')
      }
      if (data.shopDTO.businessTypeName instanceof Array) {
        data.shopDTO.businessTypeName = data.shopDTO.businessTypeName.join(',')
      }
      data.shopDTO.attachmentDTOS = [
        // 门店附件
        ...this.$getFiles(this.formDataShopDTO.ACCESS062 || []),
        ...this.$getFiles(this.formDataShopDTO.ACCESS060 || []),
        ...this.$getFiles(this.formDataShopDTO.ACCESS061 || [])
      ]
      'ACCESS062 ACCESS060 ACCESS061'.split(' ').forEach(k => {
        delete data.shopDTO[k]
      })
      // 最外层附件
      data.attachmentDTOS = isMCTrue ? [
        // 交接信息
        ...this.$getFiles(this.formData.ACCESS063 || []),
        ...this.$getFiles(this.formData.ACCESS064 || []),
        ...this.$getFiles(this.formData.ACCESS111 || [])
      ] : []
      'ACCESS063 ACCESS064 ACCESS111'.split(' ').forEach(k => {
        delete data[k]
      })
      data.type = 'B'
      return data
    },
    handleSave() {
      const data = this.getPostData()
      return shopSave(data).then(res => {
        this.$message.success('操作成功!')
        this.$pageStack.pop('onPage')
      })
    },
    handleSubmit() {
      return this.validate().then(() => {
        const data = this.getPostData(false)
        return shopSubmit(data).then(res => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('onPage')
        })
      })
    },
    handleDownTemplate(id) {
      downTemplate(id)
    },
    templateConfig() {
      getTemplateConfig('ACCESS111').then(res => {
        this.ACCESS111 = res
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.template-down{
    // display: flex;
    // align-content: center;
    display: inline-block;
    cursor: pointer;
    &>*{
      margin-right: 10px;
      color: #333;
      font-weight: 600;
    }
}
</style>